#!/usr/bin/python
# -*- coding: utf-8 -*-

#This file is part of pyLot library.
#
# pyLot is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyLot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pyLot.  If not, see <http://www.gnu.org/licenses/>.

__author__ = u'Pierre Puiseux, Guillaume Baty'
__copyright__ = u"Copyright 2011-2012 (C) andheo, Université de Pau et des Pays de l'Adour"
__credits__ = [u'Pierre Puiseux', u'Guillaume Baty']
__license__ = "GNU Lesser General Public License"

__date__ = u"18 févr. 2010"
__author__ = u"INRIA pyLot"

__all__ = [
           u'GuiScriptRunner'
           ]

from _pylot.qtgui.tools import load_designer_file
from pyLot.core import Path, Book, Datum, check_type

from Qt4.QtGui import QDialogButtonBox
from Qt4.QtCore import SIGNAL

_GuiScriptRunner, dialog = load_designer_file(u'scriptrunner.ui')

class GuiScriptRunner(dialog, _GuiScriptRunner):
  def __init__(self, history=None):
    u"""
    This class is used to select a python script file and associated parameters.
    
    History:

    You can save parameters and script paths in an history :class:`~pylot.core.Book`.
    This book must contains two keys :
      - lastscriptparams of nature "unicode"
      - lastscriptpaths of nature "Path"

    If no book passed, constructor creates a default one.
    You can access to this book by the history attribute.

    :param history: Book used to save recent parameters
    :type history: :class:`~pylot.core.Book`
    """

    dialog.__init__(self)
    self.setupUi(self)

    if history is None :
      self.history = Book(
        Datum(u'scriptpaths', Path),
        Datum(u'scriptparams', unicode)
        )
    else :
      check_type(u'history', history, Book)
      history.checkHasDatum(u'scriptparams', unicode)
      history.checkHasDatum(u'scriptpaths', Path)
      self.history = history

    self.button_ok = self.script_parameter_box.button(QDialogButtonBox.Ok)
    self.button_ok.setDisabled(True)

    self.connect(self.button_ok, SIGNAL('clicked()'), self.save)
    self.connect(self.button_add_file, SIGNAL('clicked()'), self.addFile)
    self.connect(self.button_add_directory, SIGNAL('clicked()'),
                 self.addDirectory)
    self.connect(self.button_select_script, SIGNAL('clicked()'),
                 self.selectScript)
    self.connect(self.cb_script, SIGNAL('editTextChanged(const QString)'),
                 self.checkScriptEntry)

    # fill combobox with datum value lists
    self._fillCombobox(self.cb_parameters,
                       self.history[u'scriptparams'].value_list)
    self._fillCombobox(self.cb_script,
                       self.history[u'scriptpaths'].value_list)

    # use datum value for current item
    idx = self.cb_parameters.findText(unicode(self.history(u'scriptparams')))
    self.cb_parameters.setCurrentIndex(idx)
    idx = self.cb_script.findText(unicode(self.history(u'scriptpaths')))
    self.cb_script.setCurrentIndex(idx)

  def checkScriptEntry (self):
    script = self.getScript().strip()
    if script and Path(script).isfile() :
      self.button_ok.setDisabled(False)
    else :
      self.button_ok.setDisabled(True)

  def _fillCombobox (self, combobox, text_list):
    if text_list :
      for line in text_list :
        combobox.insertItem(len(text_list), line)
    else :
      combobox.insertItem(0, u"")

  def _addPath (self, path):
    path = unicode(path)
    if path :
      line = self.getParameters()
      line += u' %s' % path
      self.cb_parameters.setItemText(0, line)

  def addDirectory (self):
    self._addPath(QFileDialog.getExistingDirectory(self))

  def addFile (self):
    line = QFileDialog.getOpenFileName(self, u"Select file",
      u"", u"pyLot parameter (*.pylotparam *.pylotdb);;All files (*)")
    self._addPath(line)

  def selectScript (self):
    path = unicode(QFileDialog.getOpenFileName(self, u"Select python script",
      u"", u"Python script (*.py *.pyc *.pyo *.pyd);;All files (*)"))
    self.cb_script.setItemText(0, path)
    self.cb_script.setCurrentIndex(0)

  def save (self):
    self.history[u'scriptparams'] = self.getParameters().strip()
    self.history[u'scriptpaths'] = self.getScript().strip()

  def getParameters (self):
    return unicode(self.cb_parameters.currentText())

  def getParametersAsList (self):
    args = self.getParameters()
    if args.strip() :
      return args.split()
    else :
      return []

  def getScript (self):
    return unicode(self.cb_script.currentText())

if __name__ == '__main__':

  import doctest
  doctest.testmod()

  import sys
  from Qt4.QtGui import QApplication

  save_list = []

  app = QApplication(sys.argv)

  line = GuiScriptRunner()
  res = line.exec_()
  print line.getScript()
  print line.getParameters()
  print line.history.infos
